package nc.appcan.sp.pub;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpClientHelper {

	public static String sendHttpReq(String urlstr, String content) throws Exception {
		HttpURLConnection con = null;
		BufferedOutputStream gzipOutstream = null;
		BufferedInputStream gzipStream = null;
		ByteArrayOutputStream baos = null;
		String reqstr = null;

		try {

			URL url = new URL(urlstr);
			con = (HttpURLConnection) url.openConnection();
			
			con.setConnectTimeout(300000);
			con.setReadTimeout(300000);
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setAllowUserInteraction(false);
			con.setUseCaches(false);
			con.setRequestMethod("POST");

			 gzipOutstream = new BufferedOutputStream(con.getOutputStream());
			gzipOutstream.write(content.getBytes("UTF-8"));
			gzipOutstream.flush();
			gzipOutstream.close();
			gzipStream = new BufferedInputStream(con.getInputStream());
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[4096];
			int len = -1;
			while ((len = gzipStream.read(buffer)) != -1 ) {
				baos.write(buffer, 0, len);
			}			
			reqstr = baos.toString("utf-8");
			//reqstr = URLDecoder.decode(reqstr, "utf-8").trim();
			reqstr.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");  
            
			
			con.disconnect();
			gzipStream.close();
			baos.close();
		}
		catch (Exception e) {
			try {
				if (con != null) {
					con.disconnect();
				}
				if (gzipOutstream != null) {
					gzipOutstream.close();
				}
				if (gzipStream != null) {
					gzipStream.close();
				}	
				if (baos != null) {
					baos.close();
				}				
			} catch (Exception e1) {
				con = null;
				gzipOutstream = null;
				gzipStream = null;
				baos = null;
				e.printStackTrace();
			}			
			throw new Exception(e.getMessage());
		}
		finally {
			try {
				if (con != null) {
					con.disconnect();
				}
				if (gzipOutstream != null) {
					gzipOutstream.close();
				}
				if (gzipStream != null) {
					gzipStream.close();
				}	
				if (baos != null) {
					baos.close();
				}				
			} catch (Exception e) {
				con = null;
				gzipOutstream = null;
				gzipStream = null;
				baos = null;
				e.printStackTrace();
			}
		}
		return reqstr;
	}

}
